package cn.sumpu.app.guoguojie.biz.impl;

import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.quartz.*;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.transaction.annotation.Transactional;

import cn.sumpu.app.guoguojie.biz.*;
import cn.sumpu.app.guoguojie.constant.Channel;
import cn.sumpu.app.guoguojie.dao.CmsContentDao;
import cn.sumpu.app.guoguojie.domain.*;
import cn.sumpu.app.guoguojie.exception.AppBusinessException;
import cn.sumpu.app.guoguojie.util.*;

public class CmsContentBizImpl extends QuartzJobBean implements CmsContentBiz,
		InitializingBean {

	private CmsContentDao cmsContentDao;
	private Scheduler scheduler;
	@Autowired
	DoingTagBiz doingTagBiz;
	@Autowired
	DoingBiz doingBiz;
	@Resource
	private IdentifierBiz identifierBiz;
	@Resource
	private PictorialBiz pictorialBiz;
	public void setScheduler(Scheduler scheduler) {
		this.scheduler = scheduler;
	}

	public void setCmsContentDao(CmsContentDao cmsContentDao) {
		this.cmsContentDao = cmsContentDao;
	}

	// 添加内容
	@Override
	@Transactional(rollbackForClassName = { "cn.sumpu.app.guoguojie.exception.AppBusinessException" }, timeout = 10)
	public void addCmsContent(CmsContent cmsContent)
			throws AppBusinessException { 
		if (Common.emptyStr(cmsContent.getIdentifier())) {
			cmsContent.setIdentifier(identifierBiz.generateId("cms_content"));
		} 
		if (cmsContent.getOrderTime() != null) {
			cmsContent.setStatus(3);
			// 预约内容
			orderContent(cmsContent);
		}
//		updateContentSort(cmsContent.getChannel(), 1, null, null, null);
//		cmsContent.setSort(1);
		Integer minSort = getMinSortByChannel(cmsContent.getChannel());
		minSort = minSort==null?1:minSort-1;
		cmsContent.setSort(minSort);
		cmsContentDao.addCmsContent(cmsContent);
	}

	// 取得内容列表
	@Override
	public List<CmsContent> getContentList(String channel, Integer number) throws AppBusinessException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("channel", channel);
		map.put("pageSize", number);
		return cmsContentDao.getContentList(map); 
	}

	// 根据内容Id的集合删除内容
	@Override
	@Transactional(rollbackForClassName = { "cn.sumpu.app.guoguojie.exception.AppBusinessException" }, timeout = 10)
	public void deleteContentByIdList(String contentIdList)
			throws AppBusinessException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("contentIdList", contentIdList);
		cmsContentDao.deleteContentByIdList(map);
	}

	// 根据频道集合取得内容Id集合
	@Override
	public List<String> getContentIdList(String channelIdList)
			throws AppBusinessException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("channel", channelIdList);
		return cmsContentDao.getContentIdList(map);
	}

	// 更新内容信息
	@Override
	@Transactional(rollbackForClassName = { "cn.sumpu.app.guoguojie.exception.AppBusinessException" }, timeout = 10)
	public void updateContentById(CmsContent cmsContent)
			throws AppBusinessException {
		//修改封面
		if(Common.notEmptyStr(cmsContent.getTagCover())){
			if(cmsContent.getStatus()==1){
				updateTagCover(cmsContent.getChannel(), cmsContent.getTagCover());
				cmsContentDao.updateContentById(cmsContent);
			}
		}else{
			// 如果该条信息状态为未发布改为预约中
			if (cmsContent.getStatus() != null) {
				if (cmsContent.getOrderTime() != null
						&& cmsContent.getStatus() == 2) {
					cmsContent.setStatus(3); 
				}
				orderContent(cmsContent);
			}
			cmsContentDao.updateContentById(cmsContent);
		}
	}

	// 根据该频道下有多少条内容
	@Override
	public Integer getContentCount(String channelId)
			throws AppBusinessException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("channel",channelId);
		return cmsContentDao.getContentCount(map);
	}

	// 根据内容Id取得这条内容的信息
	@Override
	public CmsContent getContentById(String identifier)
			throws AppBusinessException {
		return cmsContentDao.getContentById(identifier);
	}

	// 根据内容Id删除内容
	@Override
	@Transactional(rollbackForClassName = { "cn.sumpu.app.guoguojie.exception.AppBusinessException" }, timeout = 10)
	public void deleteContentById(String identifier)
			throws AppBusinessException {
//		CmsContent content = getContentById(identifier);
//		updateContentSort(content.getChannel(), -1, 1, content.getSort(), null);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("identifier", identifier);
		cmsContentDao.deleteContentById(map);
	}

	// 维护编号(type：null.全频道维护 1.删除维护(-1) 2.排序上移(+1) 3.排序下移(-1))
	@Override
	public void updateContentSort(String channelId, Integer sort, Integer type,
			Integer pos1, Integer pos2) throws AppBusinessException {
		Map<String, Object> map = new HashMap<String, Object>(); 
		map.put("channel", channelId);
		map.put("sort", sort);
		map.put("type", type);
		map.put("pos1", pos1);
		map.put("pos2", pos2);
		cmsContentDao.updateContentSort(map);
	}

	// 全部更新为已发布
	@Override
	public void updateContentAll(String channelId) throws AppBusinessException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("channel", channelId);
		cmsContentDao.updateContentAll(map);
	}

	// 执行任务
	@Override
	protected void executeInternal(JobExecutionContext context)
			throws JobExecutionException {
		synchronized(CmsContentBizImpl.class){
			try { 
				JobDataMap dataMap = context.getJobDetail().getJobDataMap();
				// 取得预约内容
				CmsContent cmsContent = (CmsContent) dataMap.get("cmsContent");
				// 如果该预约内容已经被删除就不执行了
				if (cmsContentDao.getContentById(cmsContent.getIdentifier()) == null) {
					return;
				}
				CmsContentDao cmsContentDao = (CmsContentDao) dataMap
						.get("cmsContentDao");
				// 发布预约内容
				CmsContent c = new CmsContent();
				c.setIdentifier(cmsContent.getIdentifier());
				c.setOrderTime(cmsContent.getOrderTime());
				c.setStatus(1);
				Integer minSort = getMinSortByChannel(cmsContent.getChannel());
				minSort = minSort==null?1:minSort-1;
				c.setSort(minSort);
				cmsContentDao.updateContentById(c);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	// 初始化bean完成后执行该方法
	@Override
	public void afterPropertiesSet() throws Exception {
		try {
			List<CmsContent> list = cmsContentDao.getContentByTime();
			if (list != null) {
				for (int i = 0; i < list.size(); i++) {
					orderContent(list.get(i));
				}
			}
			System.out.println("预约内容成功");
			
			
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("预约内容失败");
		}
	}
	


	// 预约发布内容
	@Override
	public void orderContent(CmsContent cmsContent) {
		try {
			// 如果预约时间为空或者已经预约过了就不再执行
			if (cmsContent.getOrderTime()==null || cmsContent.getStatus()==1) {
				return;
			} else if (scheduler.getJobDetail(
					"cmsContent" + cmsContent.getIdentifier(), null) != null) {
				scheduler.deleteJob("cmsContent" + cmsContent.getIdentifier(),
						null);
			}
			JobDetail job = new JobDetail("cmsContent"
					+ cmsContent.getIdentifier(), null, this.getClass());
			// 预约的内容
			job.getJobDataMap().put("cmsContent", cmsContent);
			job.getJobDataMap().put("cmsContentDao", cmsContentDao);
			Trigger trigger = new SimpleTrigger("cmsContent"
					+ cmsContent.getIdentifier(), null,
					cmsContent.getOrderTime());
			scheduler.scheduleJob(job, trigger);
			//如果是这条内容是未发布状态则改为预约状态
			if(cmsContent.getStatus()==2){
				CmsContent c = new CmsContent();
				c.setIdentifier(cmsContent.getIdentifier());
				c.setOrderTime(cmsContent.getOrderTime());
				c.setStatus(3);
				cmsContentDao.updateContentById(c);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 取得后台的内容列表
	@Override
	public PageModel getBackContentList(String channel, String systemTag, Integer page, String title, String description, String nickname) throws AppBusinessException {
		int pageSize = 20; 
		if (page == null)
			page = 1;
		int startId = (page - 1) * pageSize; 
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("channel", channel);
		map.put("title", title);
		map.put("description", description);
		map.put("nickname", nickname);
		map.put("pageSize", pageSize);
		map.put("startId", startId);
		List<CmsContent> list = cmsContentDao.getBackContentList(map);
		int count = cmsContentDao.getContentCount(map);
		PageModel pm = new PageModel();
		pm.setCurrentPage(page);
		pm.setList(list);
		pm.setPageSize(pageSize);
		pm.setTotalRecord(count);
		pm.setTotalPage((count + pageSize - 1) / pageSize);
		return pm;
	}

	@Override
	public List<CmsContent> getContentListByTime(String channel, Date time,
			Integer number) throws AppBusinessException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("channel", channel);
		map.put("orderTime", time);
		map.put("pageSize", number);
		return cmsContentDao.getContentListByTime(map);
	}

	// 编号对调
	@Override
	@Transactional(rollbackForClassName = { "cn.sumpu.app.guoguojie.exception.AppBusinessException" }, timeout = 10)
	public void updateContentBySort(String channelId, String contentId,
			Integer sort2) throws AppBusinessException {
		CmsContent content = getContentById(contentId);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("channel", channelId);
		map.put("sort1", content.getSort());
		map.put("sort2", sort2);
		cmsContentDao.updateContentBySort(map);
		content.setSort(sort2);
		updateContentById(content);
	}
	//查询这条微博有没有已经被推送
	@Override
	public int getTblIdentifierCount(String tblIdentifier, String channel)
			throws AppBusinessException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("tblIdentifier", tblIdentifier);
		map.put("channel", channel);
		return cmsContentDao.getTblIdentifierCount(map);
	}
	//更改封面
	@Override
	public void updateTagCover(String channel, String tagCover)
			throws AppBusinessException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("channel", channel);
		map.put("tagCover", tagCover);
		cmsContentDao.updateTagCover(map);
	}
	// 首页的格子
	@Override
	public List<CmsContent> getProductGrid(String sql)
			throws AppBusinessException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("tagCover", sql);
		return cmsContentDao.getProductGrid(map);
	}
	//这个频道下的所有内容排序都+1
	@Override
	public void updateContentAddOne(String channel)
			throws AppBusinessException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("channel", channel);
		cmsContentDao.updateContentAddOne(map);
	}
	//批量预约
	@Override
	@Transactional(rollbackForClassName = { "cn.sumpu.app.guoguojie.exception.AppBusinessException" }, timeout = 10)
	public void orderAllCmsContent(List<CmsContent> content, String orderTime)
			throws AppBusinessException {
		if(content==null || content.size()==0)
			return;
		for(CmsContent c: content){
			c.setOrderTime(DateUtil.parseDate(orderTime));
			orderContent(c);
		}
	}
	//查询爱心社活动
	@Override
	public List<CmsContent> getLoveActivity(String channel, Integer number)
			throws AppBusinessException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("channel", channel);
		map.put("pageSize", number);
		return cmsContentDao.getLoveActivity(map);
	}

	/**
	 * 首页
	 * @author grieous
	 * @param request
	 */
	@Override
	public void getIndexCmsContent(HttpServletRequest request)
			throws AppBusinessException {
		
		//首页轮播图左边广告    
		List<CmsContent> advList1=getContentList("100000014", 2);
		request.setAttribute("advList1", advList1);
		//首页轮播图下方广告一
		List<CmsContent> advList2 = getContentList("100000015", 1);
		request.setAttribute("advList2", advList2);
		//首页轮播图下方广告二
		List<CmsContent> advList3 = getContentList("100000016", 5);
		request.setAttribute("advList3", advList3);
		//首页轮播图中间广告
		List<CmsContent> advList4 = getContentList("97c97471-a2f3-4f0f-8d8d-fac45b411929", 1);
		request.setAttribute("advList4", advList4);
		//首页轮播图
		List<CmsContent> lunBoList=getContentList("f45fb5e1-9c7a-4638-8c09-b90db5d48207", 4);
		request.setAttribute("lunBoList", lunBoList);
		//入住品牌
		List<CmsContent> brandList=getContentList("8df8503d-b572-4421-85ce-d2829f471dc2", 24);
		request.setAttribute("brandList", brandList);
		//V微麻豆
		List<CmsContent> modelList=getContentList("67810947-4d84-44ea-a56f-e3de018e10b9", 5);
		request.setAttribute("modelList", modelList);
		//麻豆标签
		List<CmsContent> modelTagList=getContentList("100000017", 20);
		request.setAttribute("modelTagList", modelTagList);
		//童装配饰标签
		List<CmsContent> tagList1=getContentList("409653b0-99e5-4149-928d-139c0b748d0c", 10);
		request.setAttribute("tagList1", tagList1);
		//孕产必备标签
		List<CmsContent> tagList2=getContentList("d370bbd7-4145-4719-bace-78e80e77d7ec", 10);
		request.setAttribute("tagList2", tagList2);
		//宝宝日用标签
		List<CmsContent> tagList3=getContentList("237a05c2-77a0-4745-95da-043adbc794c0", 10);
		request.setAttribute("tagList3", tagList3);
		
		
		//潮宝们喜欢的童装
		List<CmsContent> mList2=getContentList("100000003", 6);
		request.setAttribute("mList2", mList2);
		//潮宝们喜欢的童鞋
		List<CmsContent> mList3=getContentList("100000004", 6);
		request.setAttribute("mList3", mList3);
		//潮宝们喜欢的配饰
		List<CmsContent> mList4=getContentList("100000005", 6);
		request.setAttribute("mList4", mList4);
		//准妈妈必备单品
		List<CmsContent> mList5=getContentList("100000006", 6);
		request.setAttribute("mList5", mList5);
		//宝宝们的日用洗护
		List<CmsContent> mList6=getContentList("100000007", 6);
		request.setAttribute("mList6", mList6);
		
		//潮宝们喜欢的童装标签
		List<CmsContent> mTagList2=getContentList("100000009", 13);
		request.setAttribute("mTagList2", mTagList2);
		//潮宝们喜欢的童鞋标签
		List<CmsContent> mTagList3=getContentList("100000010", 13);
		request.setAttribute("mTagList3", mTagList3);
		//潮宝们喜欢的配饰标签
		List<CmsContent> mTagList4=getContentList("100000011", 13);
		request.setAttribute("mTagList4", mTagList4);
		//准妈妈必备单品标签
		List<CmsContent> mTagList5=getContentList("100000000", 13);
		request.setAttribute("mTagList5", mTagList5);
		//宝宝们的日用洗护标签
		List<CmsContent> mTagList6=getContentList("100000012", 13);
		request.setAttribute("mTagList6", mTagList6);
		
		//贴吧动态
		List<CmsContent> hotFourmList=getContentList("19044551-bf31-4fd9-bc11-9cfcb9016a66", 5);
		request.setAttribute("hotFourmList", hotFourmList);
		//轮播图右边贴吧动态
		List<CmsContent> lbrList=getContentList("8eea6c58-6844-4c09-ac80-f2fc185e467a", 5);
		request.setAttribute("lbrList", lbrList);
		//用户动态微博信息
		List<Doing> doingList = doingBiz.getDoingNewest();
		request.setAttribute("doingList", doingList);
		//首页画报
		List<DoingPictorial> huabaoList = pictorialBiz.getPictorialByChannel("705c71ef-ebe6-403f-b819-c5cdc77a53f7", 3); 
		request.setAttribute("huabaoList", huabaoList);
		/*//首页红利会
		Bonus bonus= bonusBiz.getIndexBonus();
		request.setAttribute("bonus", bonus);
		//首页红利会使用报告
		List<DoingPictorial> baList=bonusBiz.getIndexBonusReply();
		request.setAttribute("baList", baList);*/
		//首页红利会
		List<CmsContent> bonus=getContentList("100000018", 1);
		request.setAttribute("bonus", bonus);
		//使用报告
		List<CmsContent> reportList=getContentList("100000019", 2);
		request.setAttribute("reportList", reportList);
		//友情链接
		List<CmsContent> fList=getContentList("aa1a098e-2ac5-4f42-855a-c88cc4403b45", 30);
		request.setAttribute("fList", fList);
		
	}
	/**
	 * author BruceZhang
	 * @param channel	频道ID
	 * @return	根据频道ID查询这个频道下最小序号
	 * @throws AppBusinessException
	 */
	@Override
	public Integer getMinSortByChannel(String channel) throws AppBusinessException {
		return cmsContentDao.getMinSortByChannel(channel);
	}
	/**
	 * author BruceZhang
	 * @param channel	频道ID
	 * @return	根据频道ID查询这个频道下最大序号
	 * @throws AppBusinessException
	 */
	@Override
	public Integer getMaxSortByChannel(String channel)
			throws AppBusinessException {
		return cmsContentDao.getMaxSortByChannel(channel);
	}
	@Override
	public CmsContent getContentByTable(String table,String tableId,String channel)throws AppBusinessException{
	    Map<String, Object> map = new HashMap<String, Object>();
	    map.put("tblName", table);
	    map.put("tblIdentifier", tableId);
	    map.put("channel", channel);
	    return cmsContentDao.getContentByMap(map);
	}
	/**
	 * 帮淘页面
	 * @param channel
	 * @param number
	 * @return
	 * @throws AppBusinessException
	 */
	@Override
    public List<CmsContent> getAmoysList(Integer pageSize) throws AppBusinessException {
        Map<String, Object> map = new HashMap<String, Object>();
        //0-1岁频道
        map.put("channel", "5e02f483-87bd-4d77-81d5-a64ecdc877d0");
        //1-3岁频道
        map.put("channel1", "1d48a3b9-3709-4270-81b5-0267a5b3546f");
        //3-6岁频道
        map.put("channel2", "b22c5b02-baa2-42de-ac92-09042e8ccfa2");
        //怀孕期频道
        map.put("channel3", "c1fd788e-590b-4579-b5ef-d21a9f42c92d");
        map.put("pageSize", pageSize);
        return cmsContentDao.getAmoysList(map); 
    }
	/**
	 * 帮淘列表页面
	 * 
	 */
	@Override
    public List<CmsContent> getCmsContentListForAmoy(Map<String, Object> map) throws AppBusinessException {
        return cmsContentDao.getCmsContentListForAmoy(map); 
    }
	/**
	 * 帮淘列表页面 总数
	 */
	@Override
    public int getCmsContentListForAmoyCount(Map<String, Object> map) throws AppBusinessException {
        return cmsContentDao.getCmsContentListForAmoyCount(map); 
    }
	
	@Override
	public void pushContent(HttpServletRequest request) throws AppBusinessException {
        List<CmsContent> fList = getContentList(Channel.FOOTER_LINK, 50);
        request.setAttribute("fList", fList);
	}

	
}
